using System;
using System.Text;
using System.Web.UI;
using System.Drawing;
using System.IO;
using System.ComponentModel;
[assembly: WebResource("Library.WebControls.ScaleImage.include.ScaleImage.js", "text/javascript")]
namespace Library.WebControls.ScaleImage {
	///<summary>
	/// Scale image
	///</summary>
	[ToolboxBitmap(typeof(ScaleImage), "Library.WebControls.ScaleImage.ScaleImage.bmp")]
	[DesignTimeVisible(true)]
	public class ScaleImage : System.Web.UI.WebControls.Image {
		internal static readonly Type ScaleImageType = typeof(ScaleImage);
		private string _clientInstanceName;
		///<summary>
		/// Client instance name
		///</summary>
		public string ClientInstanceName {
			get {
				if (String.IsNullOrEmpty(_clientInstanceName)) {
					_clientInstanceName = ClientID + "_ins";
				}
				return _clientInstanceName;
			}
			set {
				_clientInstanceName = value;
			}
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			if (Page != null && !Page.IsCallback) {
				RegisterClientScript();
			}
		}
		private void RegisterClientScript() {
			if (!Page.ClientScript.IsClientScriptIncludeRegistered(ScaleImageType, "Scale")) {
				Page.ClientScript.RegisterClientScriptInclude(ScaleImageType, "Scale", Page.ClientScript.GetWebResourceUrl(ScaleImageType,
												 "Library.WebControls.ScaleImage.include.ScaleImage.js"));
			}
		}
		protected override void Render(HtmlTextWriter output) {
			if (Visible) {
				if (!DesignMode) {
					Size newSize = ScaleSize();
					Width = newSize.Width;
					Height = newSize.Height;
				}
			}
			if (Visible && !DesignMode) {
				var str = new StringBuilder();
				str.Append("<script language='javascript' type='text/javascript'>");
				str.AppendFormat("var {0}=new JSScaleImage('{0}','{1}',{2},{3});", ClientInstanceName, ClientID, MaxWidth, MaxHeight);
				//str.Append(String.Format("var {0}=new JSScaleImage();window['{1}']={0};", ClientInstanceName, ClientID));
				//str.Append(String.Format("{0}._h={1};", ClientInstanceName, MaxHeight));
				//str.Append(String.Format("{0}._w={1};", ClientInstanceName, MaxWidth));
				//str.Append(String.Format("{0}._ctrId='{1}';", ClientInstanceName, ClientID));
				str.Append("</script>");
				output.Write(str.ToString());
			}
			base.Render(output);
		}


		/// <summary>
		/// Actual image height
		/// </summary>
		public int ImageHeight { get; set; }

		/// <summary>
		/// Actual image width
		/// </summary>
		public int ImageWidth { get; set; }

		/// <summary>
		/// Get the size of image after scale with max width and max height
		/// </summary>
		/// <returns></returns>
		public Size ScaleSize() {
			if (ImageHeight != 0 && ImageWidth != 0) {
				return ScaleSize(ImageHeight, ImageWidth);
			}
			if (Page == null || ImageUrl == null) {
				return new Size(MaxWidth, MaxHeight);
			}


			try {
				string realPath = Page.Server.MapPath(ImageUrl);
				if (File.Exists(realPath)) {
					Image img = Image.FromFile(realPath);
					return ScaleSize(img.Height, img.Width);
				}
			} catch { return new Size(MaxWidth, MaxHeight); }

			return new Size(MaxWidth, MaxHeight);
		}

		private Size ScaleSize(int height, int width) {
			if (height >= MaxHeight && width >= MaxWidth) {
				if (MaxHeight > MaxWidth) {
					int edge = CalculateDimesion(width, MaxWidth, height);
					if (edge > MaxHeight) {
						edge = CalculateDimesion(height, MaxHeight, width);
						return new Size(edge, MaxHeight);
					}
					return new Size(MaxWidth, edge);
				} else {
					int edge = CalculateDimesion(height, MaxHeight, width);
					if (edge > MaxWidth) {
						edge = CalculateDimesion(width, MaxWidth, height);
						return new Size(MaxWidth, edge);
					}
					return new Size(edge, MaxHeight);
				}
			}
			if (height >= MaxHeight) {
				int w = CalculateDimesion(height, MaxHeight, width);
				return new Size(w, MaxHeight);
			}
			if (width >= MaxWidth) {
				int h = CalculateDimesion(width, MaxWidth, height);
				return new Size(MaxWidth, h);
			}

			return new Size(width, height);
		}

		private static int CalculateDimesion(int oldEdge1, int newsEdge1, int oldEdge2) {
			return (int)(newsEdge1 * oldEdge2 / (float)oldEdge1);
		}

		private int _maxHeight = 100;
		/// <summary>
		/// Max image height
		/// </summary>
		public int MaxHeight {
			get { return _maxHeight; }
			set {
				if (value <= 0) {
					return;
				}
				_maxHeight = value;
			}
		}
		private int _maxWidth = 100;
		/// <summary>
		/// Max image width
		/// </summary>
		public int MaxWidth {
			get { return _maxWidth; }
			set {
				if (value <= 0) {
					return;
				}
				_maxWidth = value;
			}
		}
	}
}
